// pages/users/order/detail/index.js
// var QQMapWX = require('../../../utils/qqmap-wx-jssdk.js');
// var qqmapsdk = new QQMapWX({
//   key: 'ECTBZ-UVRCX-PGE44-7WNUI-LKW3K-CYFWP'
// });
const {
  amapKey
} = require("./../../../config/config");

//高德地图
var amapFile = require('../../../utils/amap-wx.130');
const myAmapFun = new amapFile.AMapWX({
  key: amapKey, // 你的高德地图API Key
});

const {
  getgpsforeign,
  flowGetById,
  abnormalGetById,
  dealAbnormal,
  getlatespointforeign
} = require('../../../api/api')
var timer = null
Page({
  /**
   * 页面的初始数据
   */
  data: {
    navHeight: getApp().globalData.navHeight,
    navTop: getApp().globalData.navTop,
    menuHeight: getApp().globalData.menuHeight,
    bottomLift: getApp().globalData.bottomLift,
    isPopupVisible: false,
    isHeadVisible: true,
    mapEHeight: 0,
    startTime: '',
    endTime: '',
    polygons: [],
    markers: [],
    carMarker: {
      carMarkerId: 0,
      latitude: 0,
      longitude: 0,
      carAddress: '',
      carTime: '',
      carSpeed: '',
    },
    parkCustomMarkers: [],
    // customMarkers: [],
    currentRegion: {},
    longitude: null,
    latitude: null,
    scale: 13,
    lineInfo: {},
    detail: {
      status: 0, //0等待 1接单 2已完成 -1已取消
      type: 'other',
      list: [{}, {}]
    },
    url: 'https://oss-gwzs.oss-cn-beijing.aliyuncs.com/static/static/status_cancelbg.png',
    polyline: [],
    detail: {},
    id: 'YY52461165275295536789925',
    distance: 0,
    visible: false,
    auditStatus: -1,
    audit: {
      type: 1
    },
    points: [],
    playIndex: 0,
    info: {},
    isPlay: false,
    speed: 1,
    minuteVal: 10,
    duration: 500
  },

  /**
   * 生命周期函数--监听页面加载123
   */
  onLoad: function (options) {
    this.hasPermission()
    if (options.id) {
      this.setData({
        id: options.id,
        status: parseInt(options.status)
      })
      this.checkStatus()
    }
  },
  checkStatus() {
    const {
      status
    } = this.data
    if (status === 0) {
      this.loadData()
    } else {
      this.loadAbnorlmalData()
    }
  },
  markertap(e) {
    const {
      markerId
    } = e;
    const {
      markers
    } = this.data;

    const marker = markers.find(marker => marker.id === markerId);
    if (marker != null) {
      markers.forEach((item) => {
        if ((item.id === 1 || item.id === 2) && item.callout) {
          item.callout.display = 'BYCLICK';
        } else if (item.customCallout && item.id !== 0) {
          item.customCallout.display = 'BYCLICK';
        }
      });
    }

    if (markerId === 1 || markerId === 2) {
      var markerDisplay = marker != null && marker.callout ? marker.callout.display : '';
      if (marker != null) {
        if (markerDisplay === 'BYCLICK') {
          marker.callout.display = 'ALWAYS';
        }
      }
    } else {
      var markerDisplay = marker != null && marker.customCallout ? marker.customCallout.display : '';
      console.log("markerId:" + markerId + ",markerDisplay:" + markerDisplay);
      if (marker != null) {
        if (markerDisplay === 'BYCLICK') {
          marker.customCallout.display = 'ALWAYS';
        }
      }
    }
    this.setData({
      markers: markers
    });

  },
  async loadAbnorlmalData() {
    const {
      id
    } = this.data
    const params = {
      id
    }
    const result = await abnormalGetById(params)
    if (result.status === 'onPassage') {
      this.getGpsLocation()
    }
    this.setData({
      info: result
    })
  },
  async loadData() {
    const {
      id
    } = this.data
    const params = {
      id
    }
    const result = await flowGetById(params)
    // if (result.status === 'onPassage') {
    //   this.getGpsLocation()
    // }
    //处理数据
    this.setData({
      info: result,
      latitude: result.latitudeStart,
      longitude: result.longitudeStart,
      startTime: result.startTime.substring(0, 16),
      endTime: result.endTime.substring(0, 16)
    })
    // var start=[result.latitudeStart, result.longitudeStart];
    // var end=[result.latitudeEnd, result.longitudeEnd];

    this.getGpsData(result.startTime, result.endTime);
  },
  async getGpsLocation() {
    const params = {
      plateNo: info.licensePlateNum
    }
    const result = await getlatespointforeign(params)
    this.setData({
      currentLocation: result,
      latitude: result.orgLatitude,
      longitude: result.orgLongitude
    })
    this.analyseAddress(result.orgLatitude, result.orgLongitude)
  },
  getGpsData2() {
    this.setData({
      isPopupVisible: true
    });
    // this.getGpsData(this.data.info.startTime, this.data.info.endTime);
  },
  async getGpsData(startTime, endTime) {
    wx.showLoading({
      title: '正在下载轨迹数据',
      icon: 'none'
    })
    const {
      info,
      markers
    } = this.data
    const params = {
      start: startTime,
      end: endTime,
      plateNo: info.licensePlateNum
    }
    const result = await getgpsforeign(params)
    var points = result.points;
    var parkinfos = result.parkinfos;
    var lineArr = [];
    var olongitude = null;
    var olatitude = null;
    points.forEach((item) => {
      if (olongitude != item.longitude || olatitude != item.latitude) {
        lineArr.push({
          longitude: item.longitude,
          latitude: item.latitude,
          time: item.createDate,
          speed: item.velocity
        });
      }
    });

    this.getArea()
    this.setPolyLine(lineArr)
    const start = result.startPoint;
    const end = result.endPoint;
    this.addCarMarker(markers, start, 0, "BYCLICK", null);

    this.setParkinfos(parkinfos);
    this.setData({
      points: [start, end]
    });
    //设置
    // const start = result['startPoint'];
    // const end = result[result.length - 1]
    // this.getArea(start, end)
    // this.analyseAddress(start.latitude,start.longitude)
    // this.setData({
    //   points: [start, end],
    //   lineInfo: result[0]
    // })
    // this.setData({
    //   longitude:start.longitude,
    //   latitude:start.latitude
    // });
    // console.log(this.data.lineInfo)
    wx.hideLoading()
  },
  getArea: function () {
    var that = this
    var ps = []
    const {
      info
    } = this.data
    var ps = [];
    ps.push({
      id: 1,
      latitude: info.latitudeStart,
      longitude: info.longitudeStart,
      width: 12,
      height: 20,
      iconPath: "../../../images/static/DriverLoacation_orange.png",
      callout: {
        content: info.startNetPointAddress,
        color: "#fff",
        fontSize: 13,
        padding: 10,
        borderRadius: 50,
        bgColor: "#3460FF",
        display: "BYCLICK",
        boxShadow: "5px 5px 10px #aaa"
      }
    });
    ps.push({
      id: 2,
      latitude: info.latitudeEnd,
      longitude: info.longitudeEnd,
      width: 12,
      height: 20,
      iconPath: "../../../images/static/ePoint.png",
      callout: {
        content: info.endNetPointAddress,
        color: "#fff",
        fontSize: 13,
        padding: 10,
        borderRadius: 50,
        bgColor: "#3460FF",
        display: "BYCLICK",
        boxShadow: "5px 5px 10px #aaa"
      }
    });

    this.setData({
      markers: ps
    });
    // const item = {
    //   width: 12,
    //   height: 20,
    //   latitude: start.latitude,
    //   longitude: start.longitude,
    //   iconPath: "../../../images/static/DriverLoacation_orange.png",
    //   city: info.startNetPointAddress,
    //   id: 1,
    //   customCallout: {
    //     anchorX: 40,
    //     anchorY: 5,
    //     display: 'ALWAYS'
    //   }
    // }
    // ps.push(item)
    // var obj = {
    //   id: 2,
    //   width: 12,
    //   height: 20,
    //   latitude: end.latitude,
    //   longitude: end.longitude,
    //   iconPath: "../../../images/static/ePoint.png",
    //   city: info.endNetPointAddress,
    //   operate: this.formatDate("m月d日", info.endTime) + '签收',
    //   customCallout: {
    //     anchorX: 0,
    //     anchorY: 10,
    //     display: 'ALWAYS'
    //   }
    // }
    // ps.push(obj)
    // this.setData({
    //   markers: ps,
    //   customMarkers: [1, 2]
    // })
  },
  async setParkinfos(list) {
    var that = this;
    const {
      markers,
      parkCustomMarkers,
      minuteVal
    } = this.data;
    var index = 3;
    list.forEach(item => {
      var secend = item.secend;
      if (secend > minuteVal * 60) {
        index += 1;
        const pid = index;
        parkCustomMarkers.push({
          parkMarkerId: pid,
          parkAddress: '',
          latitude: item.latitude,
          longitude: item.longitude,
          parkDuration: item.duration,
          parkStartTime: item.startTime,
          parkEndTime: item.endTime
        });
        markers.push({
          id: pid,
          latitude: item.latitude,
          longitude: item.longitude,
          width: 12,
          height: 20,
          iconPath: "../../../images/static/parking.png",
          customCallout: {
            anchorY: 0, // Y轴偏移量
            anchorX: 0, // X轴偏移量
            display: 'BYCLICK', // 'BYCLICK':点击显示; 'ALWAYS':常显
          }
          // callout: {
          //   content: '停留位置:' + address + '\n' + '停留时长(经):' + item.duration + "\n停留开始:" + item.startTime + "\n停留结束:" + item.endTime,
          //   color: "#000000",
          //   fontSize: 13,
          //   borderRadius: 2,
          //   padding: 5,
          //   bgColor: "#fff",
          //   display: "BYCLICK",
          //   boxShadow: "5px 5px 10px #aaa"
          // }
        });
        that.setData({
          parkCustomMarkers: parkCustomMarkers,
          markers: markers
        })
        // myAmapFun.getRegeo({
        //   location: item.longitude + ',' + item.latitude,
        //   success: res => {
        //     // console.log("res1:" + JSON.stringify(res));
        //     // const address = res[0].regeocodeData.formatted_address;
        //     const address = "查看位置"
        //     markers.push({
        //       id: pid,
        //       latitude: item.latitude,
        //       longitude: item.longitude,
        //       width: 12,
        //       height: 20,
        //       iconPath: "../../../images/static/parking.png",
        //       callout: {
        //         content: '停留位置:' + address + '\n' + '停留时长(经):' + item.duration + "\n停留开始:" + item.startTime + "\n停留结束:" + item.endTime,
        //         color: "#000000",
        //         fontSize: 13,
        //         borderRadius: 2,
        //         padding: 5,
        //         bgColor: "#fff",
        //         display: "BYCLICK",
        //         boxShadow: "5px 5px 10px #aaa"
        //       }
        //       // label: {
        //       //   content: '停留时长(经):' + item.duration,
        //       //   color: "#ff0000",
        //       //   fontSize: 11,
        //       //   borderRadius: 2,
        //       //   anchorX: "10",
        //       //   anchorY: "-20",
        //       //   bgColor: "#fff",
        //       //   display: "BYCLICK",
        //       //   textAlign: "right",
        //       //   boxShadow: "5px 5px 10px #aaa"
        //       // }
        //     });
        //     that.setData({
        //       markers: markers
        //     })
        //   },
        //   fail: function (error) {
        //     console.log('error');
        //   }
        // });
      }
    });
    // that.setData({
    //   markers: markers
    // })
  },
  async setPolyLine(list) {
    this.setData({
      polyline: [{
        points: list,
        color: "#00ff00",
        width: 4,
        arrowLine: true
      }]
    })
  },
  analyseAddress(latitude, longitude) {
    const self = this
    myAmapFun.getRegeo({
      location: longitude + ',' + latitude,
      success: res => {
        // console.log("res1:" + JSON.stringify(res));
        self.setData({
          currentRegion: res[0].regeocodeData.addressComponent
        })
      },
      fail: function (error) {
        console.log('error');
      }
    });
  },
  beginTrack: function () { //播放
    var that = this;
    var i = that.data.playIndex == 0 ? 0 : that.data.playIndex;
    const {
      polyline,
      markers,
      speed,
      duration
    } = this.data
    if (polyline.length < 1) {
      wx.showToast({
        title: '请先下载轨迹数据',
        icon: 'none'
      })
      return
    }
    timer = setInterval(function () {
      i += that.data.speed;
      var points = that.data.polyline[0].points;
      if ((i + 1) >= points.length) {
        that.endTrack();
      }
      var point = points[i];
      var nextPoint = points[i + 1];
      var rotate = that.rotate(point.longitude, point.latitude, nextPoint.longitude, nextPoint.latitude)
      that.addCarMarker(markers, point, rotate, "ALWAYS", null);
      that.setData({
        isPlay: true,
        playIndex: i,
        markers: markers,
        lineInfo: polyline[0].points[i]
      })
      // myAmapFun.getRegeo({
      //   location: point.longitude + ',' + point.latitude,
      //   success: res => {
      //     var address = res[0].regeocodeData.formatted_address;
      //     // console.log("res1:" + JSON.stringify(res));
      //     // self.setData({
      //     //   currentRegion: res[0].regeocodeData.addressComponent
      //     // })
      //     that.addCarMarker(markers, point, rotate, "ALWAYS", address);
      //     that.setData({
      //       isPlay: true,
      //       playIndex: i,
      //       markers: markers,
      //       lineInfo: polyline[0].points[i]
      //     })
      //   },
      //   fail: function (error) {
      //     console.log('error');
      //   }
      // });
      // that.analyseAddress(point.latitude, point.longitude);

      // that.moveTo(nextPoint, rotate);
    }, duration)
  },
  moveTo: function (point, rotate) {
    //marker移动
    let mapCtx = wx.createMapContext("map")
    mapCtx.translateMarker({
      markerId: 0,
      autoRotate: false,
      duration: 1000,
      destination: point,
      rotate: rotate
    })
  },
  rotate: function (y1, x1, y2, x2) {
    var x1 = x1;
    var y1 = y1;
    var x2 = x2;
    var y2 = y2;

    var alpha = Math.acos((y2 - y1) / Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)));
    if (x2 - x1 < 0) {
      alpha = Math.PI * 2 - alpha;
    }
    // console.log(alpha / Math.PI * 180)
    return (alpha / Math.PI * 180)
  },
  addCarMarker: function (markers, point, rotate, display, address) {
    const marker = {
      iconPath: '../../../images/static/ic_pos.png',
      id: 0,
      latitude: point.latitude,
      longitude: point.longitude,
      rotate: 45 - rotate,
      width: 15,
      height: 15,
      anchor: {
        x: 0.5,
        y: 0.5
      },
      customCallout: {
        anchorY: 0, // Y轴偏移量
        anchorX: 0, // X轴偏移量
        display: 'ALWAYS', // 'BYCLICK':点击显示; 'ALWAYS':常显
      }
      // callout: {
      //   content: point.time ? ((address!=null?( address + '\n'):'')+'时间：' + point.time + ' \n 速度：' + point.speed + ' km/h') : "无知",
      //   color: "#000000",
      //   fontSize: 13,
      //   borderRadius: 2,
      //   padding: 5,
      //   bgColor: "#fff",
      //   display: display,
      //   boxShadow: "5px 5px 10px #aaa"
      // }
    }
    if (markers.length > 2) {
      markers.splice(2, 1, marker);
    } else {
      markers.push(marker);
    }
    const {
      carMarker
    } = this.data;
    carMarker.carAddress = '';
    carMarker.latitude = point.latitude;
    carMarker.longitude = point.longitude;
    carMarker.carTime = point.time;
    carMarker.carSpeed = point.speed;
    this.setData({
      carMarker: carMarker
    })
  },
  stopTrack: function () {
    var that = this;
    that.setData({
      isPlay: false
    })
    clearInterval(timer)
  },
  endTrack: function () {
    var that = this;
    const {
      polyline,
      markers
    } = this.data
    const marker = {
      iconPath: 'https://oss-gwzs.oss-cn-beijing.aliyuncs.com/static/static/loc_icon1.png',
      id: 0,
      latitude: polyline[0].points[0].latitude,
      longitude: polyline[0].points[0].longitude,
      width: 30,
      height: 30,
      callout: {
        content: '时间：' + polyline[0].points[0].time + ' \n 速度：' + polyline[0].points[0].speed + ' km/h',
        color: "#000000",
        fontSize: 13,
        borderRadius: 2,
        bgColor: "#fff",
        display: "ALWAYS",
        boxShadow: "5px 5px 10px #aaa"
      }
    }
    markers.splice(2, 1);
    that.setData({
      playIndex: 0,
      latitude: polyline[0].points[0].latitude,
      longitude: polyline[0].points[0].longitude,
      lineInfo: polyline[0].points[0],
      markers
    })

    wx.showToast({
      title: '回放完成',
      icon: 'none'
    })
    clearInterval(timer)
  },
  callouttap: function (e) {
    var that = this;
    const {
      markerId
    } = e;
    const {
      carMarker,
      parkCustomMarkers
    } = this.data;
    console.log("markerId:" + markerId);
    if (markerId === 0) {
      myAmapFun.getRegeo({
        location: carMarker.longitude + ',' + carMarker.latitude,
        success: res => {
          const address = res[0].regeocodeData.formatted_address;
          carMarker.carAddress = address;
          that.setData({
            carMarker: carMarker
          });
        },
        fail: function (error) {
          console.log('error');
        }
      });
    } else if (markerId > 2) {
      const marker = parkCustomMarkers.find(marker => marker.parkMarkerId === markerId);
      if (marker != null) {
        if(marker.parkAddress != '') return;
        myAmapFun.getRegeo({
          location: marker.longitude + ',' + marker.latitude,
          success: res => {
            const address = res[0].regeocodeData.formatted_address;
            marker.parkAddress = address;
            that.setData({
              parkCustomMarkers: parkCustomMarkers
            });
          },
          fail: function (error) {
            console.log('error');
          }
        });
      }
    }
  },
  clickCarAddress: function () {
    console.log("clickCarAddress");
  },
  hasPermission: function () {
    var that = this;
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userLocation']) {
          that.getCurLocation();
        } else {
          console.log("未允许权限");
          wx.authorize({
            scope: 'scope.userLocation',
            success() {
              that.getCurLocation();
              console.log("success")
            },
            fail() {
              that.showPermissionDialog('需要定位权限来获取您的位置');
              console.log("fail")
            }
          })
        }
      }
    })
  },
  getCurLocation: function () {
    var that = this;
    //获取当前的地理位置、速度
    /*wx.getLocation({
      type: 'wgs84', // 默认为 wgs84 返回 gps 坐标，gcj02 返回可用于 wx.openLocation 的坐标
      success: function (res) {
        //赋值经纬度
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude,
          scale: 14,
        })
        var obj = [{
          latitude: res.latitude,
          longitude: res.longitude,
        }, {
          latitude: 22.728443,
          longitude: 108.328779
        }, ]
        that.setData({
          points: obj
        })
      }
    })*/
  },
  back() {
    wx.navigateBack()
  },
  hiddenHeader() {
    this.setData({
      isHeadVisible: false,
      mapEHeight: 500
    });
  },
  showHeader() {
    this.setData({
      isHeadVisible: true,
      mapEHeight: 0
    });
  },
  search() {
    this.setData({
      isPopupVisible: true
    });
  },
  download(e) {
    var startTime = e.detail.startTime + ":00";
    var endTime = e.detail.endTime + ":00";
    this.setData({
      minuteVal: e.detail.minute,
      duration: e.detail.duration
    })
    // this.data.minuteVal = e.detail.minute;
    // this.data.duration = e.detail.duration;
    console.log("e：" + JSON.stringify(e.detail));
    if (startTime > endTime) {
      wx.showToast({
        title: '开始时间不能大于结束时间！',
        icon: 'none'
      })
      return;
    }
    this.getGpsData(startTime, endTime);
  },
  getLine: (from, to) => {
    return new Promise((resolve, rej) => {
      let url = `https://apis.map.qq.com/ws/direction/v1/driving/?from=${from.latitude},${from.longitude}&to=${to.latitude},${to.longitude}&output=json&key=ECTBZ-UVRCX-PGE44-7WNUI-LKW3K-CYFWP`
      wx.request({
        url: url,
        method: 'get',
        success(res) {
          let coors = res.data.result.routes[0].polyline
          for (var i = 2; i < coors.length; i++) {
            coors[i] = coors[i - 2] + coors[i] / 1000000
          }
          let coors_new = [];
          for (var j = 0; j < coors.length; j++) {
            coors_new.push({
              latitude: parseFloat(coors[j]),
              longitude: parseFloat(coors[j + 1])
            })
            j++;
          }
          res.AtLastLineList = coors_new
          resolve(res)
        }
      })
    })
  },
  formatDate: function (formatStr, fdate) {
    if (fdate) {
      if (~fdate.indexOf('.')) {
        fdate = fdate.substring(0, fdate.indexOf('.'));
      }
      fdate = fdate.toString().replace('T', ' ').replace(/\-/g, '/');
      var fTime, fStr = 'ymdhis';
      if (!formatStr)
        formatStr = "y-m-d h:i:s";
      if (fdate)
        fTime = new Date(fdate);
      else
        fTime = new Date();
      var month = fTime.getMonth() + 1;
      var day = fTime.getDate();
      var hours = fTime.getHours();
      var minu = fTime.getMinutes();
      var second = fTime.getSeconds();
      month = month < 10 ? '0' + month : month;
      day = day < 10 ? '0' + day : day;
      hours = hours < 10 ? ('0' + hours) : hours;
      minu = minu < 10 ? '0' + minu : minu;
      second = second < 10 ? '0' + second : second;
      var formatArr = [
        fTime.getFullYear().toString(),
        month.toString(),
        day.toString(),
        hours.toString(),
        minu.toString(),
        second.toString()
      ]
      for (var i = 0; i < formatArr.length; i++) {
        formatStr = formatStr.replace(fStr.charAt(i), formatArr[i]);
      }
      return formatStr;
    } else {
      return "";
    }
  }
})